<template>
  <div class="wrap"
    :style="`background-image:url(${infoData.isBackImg ? infoData.BackgroundImageShow : ''});width:${infoData.isBackImg ? originW : 'auto'}px;height:${infoData.isBackImg ? originH : 'auto'}px;`">
    <img :src="infoData.BackgroundImageShow" ref="" style="display: none;" />
    <div class="content-box" :style="`height:${originH}px;`">
      <img :src="infoData.BackgroundMaterialShow" id="img_mater"
        :style="`height:${heightRef > 0 ? heightRef + 'px' : 'auto'}`" class="avator" ref="materialImg"
        v-if="infoData.isMaterialImg" />
      <video id="videoBox" class="video-wrap" ref="materialVideo"
        :style="`height:${heightRef > 0 ? heightRef + 'px' : 'auto'}`" controls autoplay loop preload="auto"
        :src="infoData.BackgroundMaterialShow" v-if="!infoData.isMaterialImg">
      </video>
      <!-- <div id="box" class="worship-item" v-show="infoData.isMaterialImg">
        <div class="text-wrap">
          <p class="content" id="contentbox"></p>
        </div>
      </div> -->
      <audio class="audio_wrap" :src="`${baseUrl}/${infoData.backgroundMusic}`" controls autoplay loop>
        <!-- <source :src="`${baseUrl}/${infoData.backgroundMusic}`"  type="audio/mp3"> -->
      </audio>
    </div>

    <video class="video_bg" id="video_bg_box" :src="infoData.BackgroundImageShow" @loadedmetadata="onVideoLoad"
      ref="bgVideo" v-if="!infoData.isBackImg">
    </video>
  </div>
</template>
<script setup name="deceased">
import { onMounted, onBeforeUnmount, ref, defineProps, watch } from 'vue';
import { baseUrl } from '../utils/http'
// import gsap from "gsap";
// import { TextPlugin } from "gsap/TextPlugin"; // 导入 TextPlugin


// gsap.registerPlugin(TextPlugin); // 注册插件
const materialImg = ref(null)
const materialVideo = ref(null)
const bgImg = ref(null)
const bgVideo = ref(null)
const originH = ref('');
const originW = ref('');
const materialImgL = ref(0)
const materialVideoL = ref(0)
const heightRef = ref('')
const infoData = ref({})
const props = defineProps({
  data: {
    type: Object,
    default: () => { }
  }
})
const testUrl = 'http://124.221.137.201:8081/Upload/Tables/SZ_CeremonyTemplate/202410051511304483/001.mp4'

// const onImageLoad = () => {
//       const img = materialImg.value;
//       // img.onload = () => {
//       //   console.log('Background image dimensions:',img, img.naturalWidth, img.naturalHeight);
//       // };
//       console.log('Background image dimensions:',originH.value,img, img.naturalWidth, img.naturalHeight,img.width);

// };

// const onVideoLoad = () => {
//   const img_mater = document.querySelector('#img_mater')
//   const videoM = document.querySelector('#videoBox')
//   const video = bgVideo.value;
//   //console.log('video', video, video.videoWidth, video.videoHeight)
//   //const videoM = materialVideo.value;
//   originH.value = video.videoHeight;
//   const w = video.videoWidth

//   img_mater?.addEventListener('load', () => {
//     //console.log('图片加载了', img_mater.width)
//     materialImgL.value = (w - img_mater.width) / 2;
//   })
//   videoM?.addEventListener('loadedmetadata', () => {
//     const w2 = videoM.videoWidth
//     materialVideoL.value = (w - w2) / 2;
//   })
// }

// 等待图片和视频都加载完成，获取尺寸后居中设置背景
const handleBackgroundSetup = async ({ bg, mater, isBackImg, isMaterialImg
}) => {
  let videobg = null
  let imagebg = null;
  let videoM = null
  let imageM = null;
  let ml = 0;
  let w = 0;
  let h = null
  // 背景是视频，素材是图片
  if (!isBackImg && isMaterialImg) {
    videobg = await loadVideo(bg);
    imageM = await loadImage(mater);
    console.log('背景是视频，素材是图片', videobg.videoWidth, imageM.width)
    w = videobg.videoWidth;
    h = videobg.videoHeight

    if (imageM.height > videobg.videoHeight) {
      const scale = 0.9; // videoM.videoWidth / videoM.videoHeight
      const mw = videoM.videoWidth * scale
      heightRef.value = h * scale;
      ml = (w - mw) / 2;
    } else {
      ml = (w - imageM.width) / 2
    }

  }
  // 背景是视频，素材是视频
  if (!isBackImg && !isMaterialImg) {
    videobg = await loadVideo(bg);
    videoM = await loadVideo(mater);

    w = videobg.videoWidth;
    h = videobg.videoHeight;
    if (videoM.videoHeight > videobg.videoHeight) {
      const scale = 1; // videoM.videoWidth / videoM.videoHeight
      const mw = videoM.videoWidth * scale
      heightRef.value = h;
      ml = (w - mw) / 2;
      console.log('背景是视频，素材是视频', scale, mw, ml)
    } else {
      ml = (w - videoM.videoWidth) / 2
    }

  }

  // 背景是图片，素材是视频
  if (isBackImg && !isMaterialImg) {
    imagebg = await loadImage(bg);
    videoM = await loadVideo(mater);
    console.log('背景是图片，素材是视频', imagebg.width, videoM.videoWidth)
    w = imagebg.width;
    h = imagebg.height;
    if (videoM.videoHeight > imagebg.height) {
      const scale = 0.9; // videoM.videoWidth / videoM.videoHeight
      const mw = videoM.videoWidth * scale
      heightRef.value = h;
      //ml = (w - mw) / 2;
      //console.log('scale',scale,mw,ml)
      ml = (w - videoM.videoWidth) / 2
    } else {
      ml = (w - videoM.videoWidth) / 2
    }
  }

  // 背景是图片，素材是图片
  if (isBackImg && isMaterialImg) {
    imagebg = await loadImage(bg);
    imageM = await loadImage(mater);
    console.log('背景是图片，素材是图片', imagebg.videoWidth, imageM.width)
    w = imagebg.width;
    h = imagebg.height;
    if (imageM.height > imagebg.height) {
      const scale = 0.9; // videoM.videoWidth / videoM.videoHeight
      const mw = imageM.width * scale
      heightRef.value = h * scale;
      ml = (w - mw) / 2;
    } else {
      ml = (w - imageM.width) / 2
    }


  }
  originW.value = w;
  originH.value = h;
  materialImgL.value = ml

  // 设置背景样式，确保素材居中
  //setBackgroundStyle(backgroundContainer.value, videoWidth, videoHeight, imageWidth, imageHeight);
};
// 加载视频并返回视频元素
const loadVideo = (videoUrl) => {
  return new Promise((resolve) => {
    const video = document.createElement('video');
    video.src = videoUrl;
    video.addEventListener('loadedmetadata', () => {
      resolve(video);
    });
  });
};

// 加载图片并返回图片元素
const loadImage = (imageUrl) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.src = imageUrl;
    img.onload = () => {
      resolve(img);
    };
  });
};

// 设置背景容器的样式
const setBackgroundStyle = (container, videoWidth, videoHeight, imageWidth, imageHeight) => {
  // 根据素材尺寸动态设置背景的居中方式
  container.style.backgroundImage = `url(${imageSrc.value})`;
  container.style.backgroundPosition = 'center center';
  container.style.backgroundSize = 'cover';

  // 可以根据视频尺寸做其他设置，比如播放视频作为背景等
  // 这里也可以根据视频的宽高设置其他样式
};

watch(() => props.data, (val) => {
  if (Object.keys(val).length) {
    const obj = { ...val };
    obj.BackgroundImageShow = baseUrl + '/' + obj.BackgroundImage;
    obj.BackgroundMaterialShow = obj.BackgroundMaterial ? baseUrl + '/' + obj.BackgroundMaterial : '';
    console.log('obj-watch', obj)
    infoData.value = obj;
    const params = {
      bg: obj.BackgroundImageShow,
      mater: obj.BackgroundMaterialShow,
      isBackImg: obj.isBackImg,
      isMaterialImg: obj.isMaterialImg,
    }

    // if (obj.isBackVideo || obj.isBackImg) {
    //   let bgRes = null;
    //   if (obj.isBackVideo) {
    //     bgRes = await checkVideoExists(bgMater)
    //   }
    //   if (obj.isBackImg) {
    //     bgRes = await checkImgExists(bgMater)
    //   }
    //   if (!bgRes) {
    //     obj.BackgroundImageShow = bgMater_online;
    //   } else {
    //     obj.BackgroundImageShow = bgMater;
    //   }
    // }

    // if (obj.isMaterialImg || obj.isMaterialVideo) {
    //   let mRes = null;
    //   if (obj.isMaterialVideo) {
    //     mRes = await checkVideoExists(mater)
    //   }
    //   if (obj.isMaterialImg) {
    //     mRes = await checkImgExists(mater)
    //   }
    //   if (!mRes) {
    //     obj.BackgroundMaterialShow = mater_online;
    //   } else {
    //     obj.BackgroundMaterialShow = mater;
    //   }
    // }

    // const music_on = await checkAudioExists(music);

    // if (music_on) {
    //   obj.backgroundMusic = music;
    // } else {
    //   obj.backgroundMusic = music_online
    // }
    //handleBackgroundSetup(params)
  }
}, {
  deep: true,
  immediate: true
})

let timeer = null


onMounted(() => {
  //showFullScreenPrompt()
  //const playbtn = document.querySelector('#playbtn');
  // setInitfn()
  // if (infoData.value.BackgroundImageShow) {
  //   if (infoData.value.isBackImg) {
  //     setInitImgfn(obj.BackgroundImageShow)
  //   } else {
  //     setInitfn(infoData.value.BackgroundImageShow)
  //   }
  // }
  // const img_mater = document.querySelector('#img_mater')
  // console.log('img_mater',img_mater)

})

onBeforeUnmount(() => {

})
</script>
<style lang="less" scoped>
@w: 1920vw;
@rw: (@w/100);
@h: 1080vh;
@rh: (@h/100);

.adaptive-size(@elementWidth, @elementHeight, @baseWidth: 1920, @baseHeight: 1080) {
  @widthRatio: (@elementWidth / @baseWidth) * 100;
  @heightRatio: (@elementHeight / @baseHeight) * 100;
  width: @widthRatio * 1vw;
  height: @heightRatio * 1vh;
}

.adaptive-font(@elementWidth, @baseWidth: 1920) {
  @widthRatio: (@elementWidth / @baseWidth) * 100;
  font-size: @widthRatio * 1vw;
}

.wrap {
  // width: 100vw;
  // height: 100%;
  //background: url('../assets/img/bg.webp') no-repeat;
  width: 100%;
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
  overflow-y: hidden;


  .content-box {
    position: relative;
    display: flex;
    align-items: center;
    // justify-content: center;
    // flex-direction: column;
    box-sizing: border-box;

    .avator {
      object-fit: contain;
      /* 确保视频填满屏幕，且保持视频比例 */
      object-position: center;
    }

    .text-wrap {
      margin-left: 20px;
      font-size: (40vw / @rw);
      color: #fff;

      .left {
        font-weight: bold;
      }
    }
  }

  .video-wrap {
    // width: 100vw;
    // height: 100vh;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    height: 50%;
    object-fit: contain;
    /* 确保视频填满屏幕，且保持视频比例 */
    object-position: center;
    background-color: transparent;
    /* 背景颜色，避免视频比例问题时的黑边 */
  }

}

.video_bg {
  position: absolute;
  left: 0;
  top: 0;
  //width: 100vw;
  //height: 100%;
  z-index: -2;
  //object-fit: cover; /* 确保视频填满屏幕，且保持视频比例 */
  background-color: transparent;
  /* 背景颜色，避免视频比例问题时的黑边 */
}

.audio_wrap {
  position: absolute;
  left: 0;
  margin: 30px 0 0 0;
  opacity: 0;
}
</style>